package com.lgj.auth.config;

import com.lgj.auth.code.token.OauthServerTokenServices;
import com.lgj.auth.code.token.DefaultOauthTokenEnhancer;
import com.lgj.auth.code.AuthPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.sql.DataSource;

/**
 * @author: guangjie.liao
 * @Date: 2022/11/16 22:42
 * @Description: 初始化相关类
 */
@Order(1)
@Configuration
public class OauthAutoConfiguration {

    @Autowired
    private DataSource dataSource;

    /**
     * 密码解析器
     **/
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new AuthPasswordEncoder();
    }

    /**
     * token增强
     * @return
     */
    @Bean
    public TokenEnhancer tokenEnhancer(){
        return new DefaultOauthTokenEnhancer();
    }

    /**
     * token生成
     */
    @Bean
    @Primary
    public AuthorizationServerTokenServices defaultTokenServices(TokenStore tokenStore,
                                                                 ClientDetailsService clientDetailsService,
                                                                 AuthenticationManager authenticationManager) {
        OauthServerTokenServices serverTokenServices =
                new OauthServerTokenServices(tokenStore, clientDetailsService, tokenEnhancer(), authenticationManager);
        return serverTokenServices;
    }

    /**
     * code 生成服务
     **/
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        // 生成的code只能使用一次（无论成功还是失败）
        return new JdbcAuthorizationCodeServices(dataSource);
    }
}
